
characterizeWinnersAndLosers <- function(mechanism, robust){
    data_match <- glue("data/stable_matchings_abc_remove_{robust}.csv") %>% 
        read.csv()
    
    df_comparison <- merge(getAssignmentRank(data_match, "mu_srda"),
                           getAssignmentRank(data_match, "mu2"),
                           by = c("id"))
    
    df_summary_winners <- df_comparison %>% 
        filter(rank < rank_benchmark | (is.na(rank_benchmark) == T & is.na(rank) == F)) %>% 
        mutate(g1 = (is.na(rank_benchmark) == T & is.na(rank) == F),
               g2 = program_id != program_id_benchmark & is.na(rank_benchmark) == F,
               g3 = program_id == program_id_benchmark & is.na(rank_benchmark) == F) %>% 
        summarize(count = n(),
                  g1 = sum(g1),
                  g2 = sum(g2),
                  g3 = sum(g3)) %>% 
        mutate(winner = 1)
    
    df_summary_losers <- df_comparison %>% 
        filter(rank > rank_benchmark | (is.na(rank_benchmark) == F & is.na(rank) == T)) %>% 
        mutate(g1 = (is.na(rank_benchmark) == F & is.na(rank) == T),
               g2 = program_id != program_id_benchmark & is.na(rank) == F,
               g3 = program_id == program_id_benchmark & is.na(rank) == F) %>% 
        summarize(count = n(),
                  g1 = sum(g1),
                  g2 = sum(g2),
                  g3 = sum(g3)) %>% 
        mutate(winner = 0)
    
    rbind(df_summary_winners, df_summary_losers) %>% 
        mutate(mechanism = mechanism,
               robust = robust)
}

getAssignmentRank <- function(df, match_variable_name){
    data_rols <- APPLICATIONS_DATA %>% 
        read_dta() %>% 
        select(all_of(c("id", "rank", "contract_id")))
    
    data_contracts <- APPLICATIONS_DATA %>%
        read_dta() %>% 
        group_by(contract_id, program_id, across(all_of(c("funding", "munkarend", "szekhely")))) %>% 
        summarise()
    
    df_output <- df %>% 
        mutate(id = sid, 
               contract_id = ifelse(get(match_variable_name) == "None", 
                                    NA, 
                                    as.numeric(get(match_variable_name)))) %>% 
        merge(., data_rols, by = c("id", "contract_id"), all.x = T) %>% 
        merge(., data_contracts, by = c("contract_id"), all.x = T) %>% 
        select(id, contract_id, program_id, rank)
    if (match_variable_name == "mu_srda"){
        colnames(df_output) <- c("id", 
                                 "contract_id_benchmark",
                                 "program_id_benchmark",
                                 "rank_benchmark")    
    }
    return(df_output)
}
